<?php

class Slide extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{slide}}':
     * @var integer $id
     * @var integer $node_id
     * @var string $title
     * @var string $picture_saved_path
     * @var string $url
     * @var integer $status
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{slide}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('node_id, title, target', 'required'),
            array('node_id, status, order_pos, created, updated', 'numerical', 'integerOnly' => true),
            array('url', 'url'),
            array('title, picture_saved_path, url', 'length', 'max' => 200),
            array('target', 'length', 'max' => 10),
            array('picture_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => 'jpg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'title' => Yii::t('slide', 'title'),
            'picture_saved_path' => Yii::t('slide', 'picture_saved_path'),
            'url' => Yii::t('slide', 'url'),
            'target' => Yii::t('slide', 'target'),
            'status' => Yii::t('options', 'status'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    const TARGET_BLANK = '_blank';
    const TARGET_SELF = '_self';
    public function getTargetOptions() {
        return array(
            self::TARGET_BLANK   => Yii::t('slide', 'target_blank'),
            self::TARGET_SELF => Yii::t('slide', 'target_self'),
        );
    }

    // 格式化更新时间
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxFormat() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/slide/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#status{$this->id}",
            ),
            array('id' => "status{$this->id}")
        );
    }

    // “链接打开方式”文字格式
    public function getTargetTextFormat() {
        $options = $this->targetOptions;
        return (isset($options[$this->target])) ? $options[$this->target] : 'unknown';
    }

    /**
     * get logo picture saved path
     * @return string
     */
    public function getPicturePath() {
        return Yii::app()->basePath . '/../upload/slide/' . $this->picture_saved_path;
    }

    public function getPictureSource() {
        return Yii::app()->baseUrl . '/upload/slide/' . $this->picture_saved_path;
    }
    
    private $_original_picture_saved_path;
    public function afterFind() {
        $this->_original_picture_saved_path = $this->picture_saved_path;
    }

    protected function beforeSave() {
        parent::beforeSave();
        $uploading_file = CUploadedFile::getInstance($this, 'picture_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                @unlink(Slide::model()->findByPk($this->id)->picture_saved_path);
            }
            $filename = md5($this->url . $this->title) . '.' . $uploading_file->getExtensionName();
            $this->picture_saved_path = $filename;
            $uploading_file->saveAs(Yii::app()->basePath . '/../upload/slide/' . $filename);
        } else {
            $this->picture_saved_path = $this->_original_picture_saved_path;
        }

        return true;
    }

    // 删除记录的同时删除 logo 文件
    public function afterDelete() {
        @unlink($this->picturePath);
    }

    protected function findBase($type = 'recent', $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        switch ($type) {
            case 'recent':
                $criteria->order = 'created DESC';
                break;
            default:
                $criteria->order = 'created DESC';
                break;
        }
        $criteria->limit = $limit;

        return self::model()->findAll($criteria);
    }

    // 最新
    public function findRecent($node = null, $limit = 12) {
        return $this->findBase('recent', $node, $limit);
    }
    
}